package airport.server.DAO;

import airport.server.pojo.Hotel;
import airport.server.pojo.Vol;
import airport.shared.beans.HotelBean;
import airport.shared.beans.VolBean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Romain on 13/02/15.
 */
public class VolDAO extends DAO<VolBean> {

	public ArrayList<VolBean> selectAll() {
		List<Vol> volList;
		ArrayList<VolBean> volBeanList = new ArrayList<VolBean>();
		Vol vol;

        connection();
        volList = session.createQuery("select distinct v from Vol v order by v.date_depart desc,date_arrivee desc ").list();

		Iterator i = volList.iterator();
		while (i.hasNext()) {
			vol = (Vol) i.next();
			volBeanList.add(pojoToBean(vol));
		}

        commitAndClose();

        return volBeanList;
    }

	@Override
	public String save(VolBean v) {
		connection();
		session.save(beanToPojo(v));
		commitAndClose();

		return "Vol enregistré";
	}

	@Override
	public String update(VolBean v) {
		connection();
		session.update(beanToPojo(v));
		commitAndClose();

		return "Vol mis à jour";
	}

	@Override
	public String delete(VolBean v) {
		connection();
        session.delete(beanToPojo(v));
        commitAndClose();

		return "Vol supprimé";
	}

	private VolBean pojoToBean(Vol vol) {
		VolBean volBean = new VolBean();
		volBean.setId(vol.getIduser());
		volBean.setDate_A(vol.getDate_A());
		volBean.setDate_D(vol.getDate_D());
		volBean.setLieu_A(vol.getLieu_A());
		volBean.setLieu_D(vol.getLieu_D());
		volBean.setTarif(vol.getTarif());

        for (Hotel hotel : vol.getHotels()) {
            volBean.getHotels().add(PojoHotelToBean(hotel));
        }

        volBean.setPanneaux(vol.getPanneau().size());


        return volBean;
    }

	private Vol beanToPojo(VolBean volBean) {
		Vol vol = new Vol();
		vol.setIduser(volBean.getId());
		vol.setDate_A(volBean.getDate_A());
		vol.setDate_D(volBean.getDate_D());
		vol.setLieu_A(volBean.getLieu_A());
		vol.setLieu_D(volBean.getLieu_D());
		vol.setTarif(volBean.getTarif());

        for (HotelBean bean : volBean.getHotels()) {
            vol.getHotels().add(beanToPojoHotel(bean));
        }

		return vol;
	}

    private Hotel beanToPojoHotel(HotelBean hotelBean) {
        Hotel hotel = new Hotel();
        hotel.setIdhotel(hotelBean.getIdhotel());
        hotel.setNom(hotelBean.getNom());
        hotel.setAdresse(hotelBean.getAdresse());
        hotel.setStanding(hotelBean.getStanding());
        hotel.setTarif(hotelBean.getTarif());

        return hotel;
    }

    private HotelBean PojoHotelToBean(Hotel hotel) {
        HotelBean hotelBean = new HotelBean();
        hotelBean.setIdhotel(hotel.getIdhotel());
        hotelBean.setNom(hotel.getNom());
        hotelBean.setAdresse(hotel.getAdresse());
        hotelBean.setStanding(hotel.getStanding());
        hotelBean.setTarif(hotel.getTarif());

        return hotelBean;
    }

}
